package com.taiping.smart_ocr.utils;

import org.apache.commons.io.FileUtils;
import sun.misc.BASE64Encoder;

import java.io.*;
import java.nio.charset.StandardCharsets;

public class ImageUtil {

    /**
     * @param imagePath 传入的图片路径包括文件名
     * @return imgBase64Str 图片转化后的 Base64 编码
     * 这个工具类可以输入图片转成base64输出
     */
    public static String GetBase64StrFromImage(String imagePath) throws IOException {
        InputStream in = null;
        byte[] data = null;
        try {//读取图片字节数组
            in = new FileInputStream(imagePath);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace(); }
        BASE64Encoder encoder = new BASE64Encoder();
        return getOneLine(encoder.encode(data));//将 Base64 编码字节数组转为字符串返回
    }

    public static String getOneLine(String withr) throws IOException {
        StringReader sr = new StringReader(withr);
        BufferedReader br = new BufferedReader(sr);
        String line = null;
        StringBuffer temp = new StringBuffer();
        try{
            while((line=br.readLine())!=null){
                temp.append(line);
            }
            br.close();
            sr.close();
        }catch(Exception e){
            e.printStackTrace();
        }
        FileUtils.writeStringToFile(new File("ft-test/doc/smart-ocr-ut/ziyan/902-imgcls/request1-image_cls.txt"),temp.toString(), StandardCharsets.UTF_8);
        return temp.toString(); }

    public static void main(String[] args) throws IOException {
        GetBase64StrFromImage("ft-test/doc/smart-ocr-ut/ziyan/902-imgcls/request1-image_cls.jpg");
    }

    public static String build_small_str(String photo) {
        if (photo == null || photo.length() < 30)
            return photo;
        String ret = String.format("big string len = %d, ", photo.length());
        ret += photo.substring(0, 10);
        ret += "..";
        ret += photo.substring(photo.length() - 10);
        return ret;
    }

}
